package yns.springboot.common.sample.page.impl;

import java.util.List;

import org.springframework.stereotype.Component;

import yns.springboot.common.sample.base.bean.BaseBean;
import yns.springboot.common.sample.base.dao.BaseDao;
import yns.springboot.common.sample.page.Pagination;
import yns.springboot.common.sample.page.PaginationInfo;
import yns.springboot.common.sample.page.PaginationSearchInfo;

@Component
public class PaginationImpl<T extends BaseBean> implements Pagination<T> {

	@Override
	public PaginationInfo<T> paging(BaseDao<T> dao, PaginationInfo<T> paginationInfo) {
		Integer pageSize = paginationInfo.getPageSize();
		Integer currentPage = paginationInfo.getCurrentPage();
		Integer totalCount = paginationInfo.getTotalCount();
		Integer totalPage = paginationInfo.getTotalPage();
		Integer startNum = paginationInfo.getStartNum();
		Integer endNum = paginationInfo.getEndNum();

		if (pageSize == null || pageSize < 0) {
			pageSize = 20;
		}

		if (currentPage == null || currentPage < 0) {
			currentPage = 1;
		}

		totalCount = dao.getTotalCount();
		totalPage = totalCount / pageSize;

		startNum = (currentPage - 1) * pageSize;

		List<T> dataList = dao.getPage(startNum, pageSize);

		PaginationInfo<T> pagingResults = new PaginationInfo<T>();
		pagingResults.setCurrentPage(currentPage);
		pagingResults.setDataList(dataList);
		pagingResults.setEndNum(endNum);
		pagingResults.setStartNum(startNum);
		pagingResults.setTotalCount(totalCount);
		pagingResults.setTotalPage(totalPage);

		return pagingResults;
	}

	@Override
	public PaginationSearchInfo<T> search(BaseDao<T> dao, PaginationSearchInfo<T> paginationSearchInfo) {
		Integer pageSize = paginationSearchInfo.getPageSize();
		Integer currentPage = paginationSearchInfo.getCurrentPage();
		Integer totalCount = paginationSearchInfo.getTotalCount();
		Integer totalPage = paginationSearchInfo.getTotalPage();
		Integer startNum = paginationSearchInfo.getStartNum();
		Integer endNum = paginationSearchInfo.getEndNum();
		T searchInfo = paginationSearchInfo.getSearchInfo();

		if (pageSize == null || pageSize < 0) {
			pageSize = 20;
		}

		if (currentPage == null || currentPage < 0) {
			currentPage = 1;
		}

		totalCount = dao.getTotalCount();
		totalPage = totalCount / pageSize;

		startNum = (currentPage - 1) * pageSize;

		List<T> dataList = dao.search(startNum, pageSize,searchInfo);

		PaginationSearchInfo<T> pagingResults = new PaginationSearchInfo<T>();
		pagingResults.setCurrentPage(currentPage);
		pagingResults.setDataList(dataList);
		pagingResults.setEndNum(endNum);
		pagingResults.setStartNum(startNum);
		pagingResults.setTotalCount(totalCount);
		pagingResults.setTotalPage(totalPage);

		return pagingResults;
	}

}
